package vip.xiaonuo.dev.modular.sms.util.hkust;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Objects;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;

/**
 * HTTP工具类
 * @author qinguangrui
 *
 */
public class HttpUtils {

	/**
	 * GET请求
	 * @param url 请求URL
	 * @return String 返回结果
	 */
	public static String httpGet(String url) {

		HttpGet httpGet = new HttpGet(url);
		CloseableHttpClient client = getClient();
		String respContent = null;
		System.out.println("开始执行请求");
		try {
			HttpResponse resp = client.execute(httpGet);
			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity he = resp.getEntity();
				respContent = EntityUtils.toString(he, "UTF-8");
			}
		} catch (IOException e) {
			System.err.println("响应失败："+e.getMessage());
		} finally {
			IOUtils.close(client);
		}
		return respContent;
	}

	/**
	 * 获取http客户端
	 * @return CloseableHttpClient 返回结果
	 */
	private static CloseableHttpClient getClient() {
		SSLContextBuilder builder = new SSLContextBuilder();
		// 全部信任 不做身份鉴定
		try {
			builder.loadTrustMaterial(null, new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
					return true;
				}
			});
		} catch (NoSuchAlgorithmException | KeyStoreException e1) {
			System.err.println("SSL鉴定失败："+e1.getMessage());
		}
		SSLConnectionSocketFactory sslsf = null;
		try {
			sslsf = new SSLConnectionSocketFactory(builder.build(),
					new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
		} catch (KeyManagementException | NoSuchAlgorithmException e1) {
			System.err.println("SSL连接失败："+e1.getMessage());
		}
		Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
		cm.setMaxTotal(200);// max connection
		return HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).setConnectionManagerShared(true)
				.build();
	}

	/**
	 * Post请求
	 * @param url URL地址
	 * @param jsonParam  json参数
	 * @return String 返回结果
	 */
	public static String httpPostWithJSON(String url, JSONObject jsonParam) {

		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient client = getClient();
		String respContent = null;
		if (!Objects.isNull(jsonParam)) {
			StringEntity entity = new StringEntity(jsonParam.toJSONString(), "utf-8");// 解决中文乱码问题
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			httpPost.setEntity(entity);
		}
		System.out.println("开始执行请求");

		try {
			HttpResponse resp = client.execute(httpPost);
			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity he = resp.getEntity();
				respContent = EntityUtils.toString(he, "UTF-8");
			}
		} catch (IOException e) {
			System.err.println("响应失败："+ e.getMessage());
		} finally {
			IOUtils.close(client);
		}
		return respContent;
	}

	/**
	 * POST请求
	 * @param url url地址
	 * @param parms 参数列表
	 * @return String 返回结果
	 */
	public static String httpPostWithParms(String url, List<BasicNameValuePair> parms) {
		HttpPost httpPost = new HttpPost(url);

		CloseableHttpClient client = getClient();
		String respContent = null;

		System.out.println("开始执行请求");

		try {
			HttpEntity httpEntity = new UrlEncodedFormEntity(parms, "UTF-8");
			httpPost.setEntity(httpEntity);
			HttpResponse resp = client.execute(httpPost);
			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity he = resp.getEntity();
				respContent = EntityUtils.toString(he, "UTF-8");
			}
		} catch (IOException e) {
			System.err.println("响应失败："+ e.getMessage());
		} finally {
			IOUtils.close(client);
		}
		return respContent;
	}
}
